<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
            <el-input v-model="listQuery.fsiteNo" clearable class="filter-item" style="width: 200px;" placeholder="请输入市/区/学校"/>
        <el-input v-model.number="listQuery.fscoreFlag" clearable class="filter-item" style="width: 200px;" placeholder="请输入统计范围"/>
      <el-input v-model="listQuery.fparafield" clearable class="filter-item" style="width: 200px;" placeholder="请输入参数字段"/>
        <el-input v-model.number="listQuery.feuipmentid" clearable class="filter-item" style="width: 200px;" placeholder="请输入设备ID"/>
        <el-input v-model.number="listQuery.flevelno" clearable class="filter-item" style="width: 200px;" placeholder="请输入风险等级编号"/>
        <el-input v-model.number="listQuery.fstate" clearable class="filter-item" style="width: 200px;" placeholder="请输入设定状态"/>
      <el-input v-model="listQuery.foperator" clearable class="filter-item" style="width: 200px;" placeholder="请输入操作员"/>
      <el-date-picker v-model="listQuery.fupddate" type="datetime" placeholder="请输入修改时间"></el-date-picker>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button><!-- v-permission="[':tsWarring:read']"-->
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button><!-- v-permission="[':tsWarring:create']"-->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" stripe element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column :index="indexMethod" align="center" label="序" type="index" />
      <el-table-column align="right" label="市/区/学校" prop="fsiteNo" />
      <el-table-column align="right" label="统计范围" prop="fscoreFlag" />
      <el-table-column align="right" label="参数字段" prop="fparafield" />
      <el-table-column align="right" label="起始值" prop="fbegnum" />
      <el-table-column align="right" label="结束值" prop="fendnum" />
      <el-table-column align="right" label="报警说明" prop="fdescribe" />
      <el-table-column align="right" label="设备ID" prop="feuipmentid" />
      <el-table-column align="right" label="风险等级编号" prop="flevelno" />
      <el-table-column align="right" label="第几次触发" prop="turn" />
      <el-table-column align="right" label="报警时间间隔" prop="interval" />
      <el-table-column align="right" label="是否发送消息" prop="fsendmsg" />
      <el-table-column align="right" label="是否发送邮件" prop="fsendemail" />
      <el-table-column align="right" label="设定状态" prop="fstate" />
      <el-table-column align="right" label="操作员" prop="foperator" />
      <el-table-column :formatter="datetimeFormat"align="right" label="修改时间" prop="fupddate" />
      <el-table-column align="center" label="操作员" prop="foperator" />
      <el-table-column align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" class="button-margin" @click="handleUpdate(scope.row)">编辑</el-button><!-- v-permission="[':tsWarring:update']"-->
          <el-button type="danger" size="mini" class="button-margin" @click="handleDelete(scope.row)">删除</el-button><!-- v-permission="[':tsWarring:delete']"-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog width="auto" top="0vh" :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="auto">
        <el-row>
          <el-col :span="8">
<!--            <el-form-item label="设备ID" prop="feuipmentid">
              <el-input v-model.number="dataForm.feuipmentid"/>
            </el-form-item>-->
            <el-form-item class='required' label="设备名称" prop="fequipmenttag">
              <div
                v-if="dialogStatus == 'create'"
                style="
                  display: flex;
                  justify-content: flex-start;
                  align-items: center;
                "
              >
                <el-input
                  v-model="dataForm.fequipmenttag"
                />
                <i
                  class="el-icon-search selectI"
                  @click="searchDialogEequipmentInfo()"
                />
              </div>
              <div
                v-else
                style="
                  display: flex;
                  justify-content: flex-start;
                  align-items: center;
                "
              >
                <el-input
                  disabled
                  v-model="dataForm.fequipmenttag"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="统计范围" prop="fscoreFlag">
              <el-select :disabled="dialogStatus==='update'" v-model="dataForm.fscoreFlag" class="filter-item" placeholder="请选择统计范围"> <!--@change="changeFscoreFlag2(dataForm.fscoreFlag)"-->
                <el-option v-for="(key, value) in flagMap" :key="key" :label="key" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学校名称" prop="fsiteNo">
              <el-select v-model="dataForm.fsiteNo" clearable filterable placeholder="请选择">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="参数字段" prop="fparafield">
              <el-input v-model="dataForm.fparafield"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="起始值" prop="fbegnum">
              <el-input v-model="dataForm.fbegnum"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束值" prop="fendnum">
              <el-input v-model="dataForm.fendnum"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="报警说明" prop="fdescribe">
              <el-input v-model="dataForm.fdescribe"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="风险等级编号" prop="flevelno">
              <el-input v-model.number="dataForm.flevelno"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="第几次触发" prop="turn">
              <el-input v-model.number="dataForm.turn"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="报警时间间隔" prop="interval">
              <el-input v-model.number="dataForm.interval"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否发送消息" prop="fsendmsg">
              <el-input v-model.number="dataForm.fsendmsg"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否发送邮件" prop="fsendemail">
              <el-input v-model.number="dataForm.fsendemail"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="设定状态" prop="fstate">
              <el-input v-model.number="dataForm.fstate"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作员" prop="foperator">
              <el-input v-model="dataForm.foperator"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="修改时间" prop="fupddate">
              <el-date-picker v-model="dataForm.fupddate" type="datetime"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-tabs type="border-card">
        <el-tab-pane label="人员列表">
          <div class="filter-container">
            <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleUpdate1(dataForm.fsiteNo)">添加人员</el-button><!-- v-permission="['equipment:eqtDict:create']"-->
            <el-table v-loading="listLoading" :data="dataForm.details2" element-loading-text="正在查询中。。。" border fit highlight-current-row>

              <el-table-column :index="indexMethod" align="center" label="序" type="index"/>
              <el-table-column align="center" label="人员名称" prop="username"/>
              <el-table-column align="center" width="140" label="操作" class-name="small-padding">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" @click="handleDelete1(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-tabs type="border-card">
        <el-tab-pane label="教室列表">
          <div class="filter-container">
            <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleUpdate2(dataForm.fsiteNo)">添加教室</el-button><!-- v-permission="['equipment:eqtDict:create']"-->
            <el-table v-loading="listLoading" :data="dataForm.details" element-loading-text="正在查询中。。。" border fit highlight-current-row>

              <el-table-column :index="indexMethod" align="center" label="序" type="index"/>
              <el-table-column align="center" label="教室名称" prop="fpointName"/>
              <el-table-column align="center" width="140" label="操作" class-name="small-padding">
                <template slot-scope="scope">
                  <el-button type="danger" size="mini" @click="handleDelete2(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible1">
      <el-form ref="dataForm1" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-table ref="multipleTable" :data="details2" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="fuserno" label="人员编号" width="120"/>
          <el-table-column prop="username" label="人员名称" show-overflow-tooltip/>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取消</el-button>
        <el-button type="primary" @click="addData">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible2">
      <el-form ref="dataForm2" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-table ref="multipleTable" :data="details" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange2">
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="fpointNo" label="教室编号" width="120"/>
          <el-table-column prop="fpointName" label="教室名称" show-overflow-tooltip/>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取消</el-button>
        <el-button type="primary" @click="addData2">确定</el-button>
      </div>
    </el-dialog>
    <equipmentInfoDialog
      :equipmentInfoVisible.sync="equipmentInfoVisible"
      :tableColor="tableColor"
      @equipmentInfoDialog="equipmentInfoDialogValue"
    />
  </div>
</template>

<style>
  .button-margin {
    margin : 2px 0px;
  }
  .el-button+.el-button {
    margin-left: 1px;
  }
</style>

<script>
import { listtsWarring, createtsWarring, updatetsWarring, deletetsWarring } from '@/api/tsWarring'
import { listPointByFsiteNo, listUserByFsiteNo } from '@/api/airAlarm'
import { fsiteOptionsByLevel, getFequipmentbarcode } from '@/api/area'
import EquipmentInfoDialog from "@/components/EquipmentInfoDialog";
import {
  tableColor,
  titleColor,
  exportColor,
  buttonColor,
} from "@/filters/index";
import Pagination from '@/components/Pagination'
import moment from 'moment'

const flagMap = {
  1: '学校',
  2: '教室'
}

export default {
  name: 'ATsWarring',
  components: { Pagination, EquipmentInfoDialog },
  filters: {
    flagFilter(type) {
      return flagMap[type]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      fsiteNoBelongOptions: null,
      details2Tmp: [],
      detailsTmp: [],
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      multipleSelection: [],
      multipleSelection2: [],
      multiple: [],
      multiple2: [],
      dialogStatus1: '',
      dialogStatus2: '',
      details2: [],
      details: [],
      equipmentInfoVisible: false,
      tableColor,
      titleColor,
      exportColor,
      buttonColor: buttonColor,
      flagMap,
      listQuery: {
        page: 1,
        limit: 20,
        fsiteNo: undefined,
        fscoreFlag: undefined,
        fparafield: undefined,
        fbegnum: undefined,
        fendnum: undefined,
        fdescribe: undefined,
        feuipmentid: undefined,
        flevelno: undefined,
        turn: undefined,
        interval: undefined,
        fsendmsg: undefined,
        fsendemail: undefined,
        fstate: undefined,
        foperator: undefined,
        fupddate: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        fwarringno: undefined,
        fsiteNo: undefined,
        fscoreFlag: undefined,
        fparafield: undefined,
        fbegnum: undefined,
        fendnum: undefined,
        fdescribe: undefined,
        feuipmentid: undefined,
        flevelno: undefined,
        turn: undefined,
        interval: undefined,
        fsendmsg: undefined,
        fsendemail: undefined,
        fstate: undefined,
        foperator: undefined,
        fupddate: undefined,
        id: undefined,
        details2: [],
        details: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        fsiteNo: [
          { required: true, message: '市/区/学校不能为空' },


        ],
        fscoreFlag: [
          { required: true, message: '统计范围不能为空' },

        ],
        fparafield: [
          { required: true, message: '参数字段不能为空' },


        ],
        fbegnum: [



        ],
        fendnum: [



        ],
        fdescribe: [



        ],
        feuipmentid: [
          { required: true, message: '设备ID不能为空' },
          { type: 'number', message: '设备ID必须为数字值' },

        ],
        flevelno: [
          { required: true, message: '风险等级编号不能为空' },
          { type: 'number', message: '风险等级编号必须为数字值' },

        ],
        turn: [

          { type: 'number', message: '第几次触发必须为数字值' },

        ],
        interval: [

          { type: 'number', message: '报警时间间隔必须为数字值' },

        ],
        fsendmsg: [
          { required: true, message: '是否发送消息不能为空' },
          { type: 'number', message: '是否发送消息必须为数字值' },

        ],
        fsendemail: [
          { required: true, message: '是否发送邮件不能为空' },
          { type: 'number', message: '是否发送邮件必须为数字值' },

        ],
        fstate: [
          { required: true, message: '设定状态不能为空' },
          { type: 'number', message: '设定状态必须为数字值' },

        ],
        foperator: [



        ],
        fupddate: [



        ],
      }
    }
  },
  created() {
    this.getList()
    fsiteOptionsByLevel(3) // fsiteNoBelongOptions(2)
      .then(response => {
        this.fsiteNoBelongOptions = response.data.data.list
      })
      .catch(() => {
        this.fsiteNoBelongOptions = []
      })
  },
  methods: {
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    formatSite: function(row, column) {
      if(this.fsiteNoBelongOptions){
        for (let i = 0; i < this.fsiteNoBelongOptions.length; i++) {
          if (row.fsiteNo === this.fsiteNoBelongOptions[i].value) {
            return this.fsiteNoBelongOptions[i].label
          }
        }
        return ''
      }else{
        return ''
      }
    },
    getList() {
      this.listLoading = true
      listtsWarring(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        fwarringno: undefined,
        fsiteNo: undefined,
        fscoreFlag: undefined,
        fparafield: undefined,
        fbegnum: undefined,
        fendnum: undefined,
        fdescribe: undefined,
        feuipmentid: undefined,
        flevelno: undefined,
        turn: undefined,
        interval: undefined,
        fsendmsg: undefined,
        fsendemail: undefined,
        fstate: undefined,
        foperator: undefined,
        fupddate: undefined,
        id: undefined,
        details2: [],
        details: [],
      }
    },
    // 设备信息弹出框
    searchDialogEequipmentInfo() {
      this.equipmentInfoVisible = true;
    },
    // 设备信息弹出框
    equipmentInfoDialogValue(value) {
      this.dataForm.feuipmentid = value.info.feuipmentid;
      this.dataForm.fequipmenttag = value.info.fequipmentname;
      this.dataForm.fequipmenttype = value.info.fequipmenttype;
      this.dataForm.fspec = value.info.fspec;
      /*getFequipmentbarcode({ feuipmentid: value.info.feuipmentid })
        .then((response) => {
          if (response) {
            this.dataForm.fequipmentbarcode = response.data.data;
          }
        })
        .catch(() => {
          this.dataForm.fequipmentbarcode = "";
        });*/
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createtsWarring(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加ATsWarring成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.dataForm.fscoreFlag = row.fscoreFlag.toString()
      this.details2Tmp = []
      this.detailsTmp = []
      row.details2.forEach(v => {
        this.details2Tmp.push(v)
      })
      row.details.forEach(v => {
        this.detailsTmp.push(v)
      })
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updatetsWarring(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新ATsWarring成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除ATsWarring', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletetsWarring(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除ATsWarring成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      })
    },
    addData() {
      this.dialogFormVisible1 = false
      for (var i in this.multipleSelection) {
        var atsUser = this.multipleSelection[i]
        var canAdd = true
        for (var j in this.dataForm.details2) {
          if (atsUser.fuserno + '' === this.dataForm.details2[j].fuserno) {
            canAdd = false
            break
          }
        }
        if (canAdd) {
          atsUser.fwarringno = this.dataForm.fwarringno
          this.dataForm.details2.push(atsUser)
          this.multiple.push(atsUser)
        }
      }
    },
    addData2() {
      console.log("aaaaaaaaaaa")
      this.dialogFormVisible2 = false
      console.log("bbbbbbbbbb")
      for (var i in this.multipleSelection2) {
        console.log("ccccccccccccc")
        var atsUser = this.multipleSelection2[i]
        console.log("dddddddddddddddd")
        var canAdd = true
        for (var j in this.dataForm.details) {
          console.log("eeeeeeeeeeeeeeeee")
          if (atsUser.fpointNo === this.dataForm.details[j].fpointNo) {
            console.log("fffffffffffff")
            canAdd = false
            break
          }
        }
        if (canAdd) {
          console.log("ggggggggggggggg")
          atsUser.fwarringno = this.dataForm.fwarringno
          console.log("hhhhhhhhhhhhh")
          this.dataForm.details.push(atsUser)
          console.log("iiiiiiiiiiiiii")
          this.multiple2.push(atsUser)
          console.log("jjjjjjjjjjjj")
        }
      }
    },
    cancel() {
      this.dialogFormVisible = false
      this.multiple = []
      this.multiple2 = []
      this.list.forEach(v => {
        if (v.fwarringno === this.dataForm.fwarringno) {
          this.dataForm.details2 = this.details2Tmp
          this.dataForm.details = this.detailsTmp
          const index = this.list.indexOf(v)
          this.list.splice(index, 1, this.dataForm)
          return
        }
      })
    },
    handleUpdate1(fsiteNo) {
      if (fsiteNo == null) {
        this.$notify.info({
          title: '',
          message: '请先选择学校'
        })
        return
      }
      listUserByFsiteNo(fsiteNo)
        .then(response => {
          this.details2 = response.data.data.list
        })
        .catch(() => {
          this.details2 = []
        })
      this.dialogStatus1 = 'update'
      this.dialogFormVisible1 = true
      this.multipleSelection = []
      this.$nextTick(() => {
        this.$refs['dataForm1'].clearValidate()
      })
    },
    handleUpdate2(fsiteNo) {
      if (fsiteNo == null) {
        this.$notify.info({
          title: '',
          message: '请先选择学校'
        })
        return
      }
      listPointByFsiteNo(fsiteNo)
        .then(response => {
          this.details = response.data.data.list
        })
      this.dialogStatus2 = 'update'
      this.dialogFormVisible2 = true
      this.multipleSelection2 = []
      this.$nextTick(() => {
        this.$refs['dataForm2'].clearValidate()
      })
    },
    handleDelete1(row) {
      this.dataForm.details2.pop(row)
    },
    handleDelete2(row) {
      this.dataForm.details.pop(row)
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSelectionChange2(val) {
      this.multipleSelection2 = val
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>
